#region

using System;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration;
using System.Diagnostics;
using System.Linq;
using CNav.DataEntity;
using log4net;

#endregion

namespace CNav.Repository.UoV
{
    public class DataBaseContext : CNavEntities, IDbContext
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(DataBaseContext));

        static DataBaseContext()
        {
            Database.SetInitializer<DataBaseContext>(null);
        }

        public DataBaseContext()
            : base("Name=Entity.Connection")
        {
            Configuration.LazyLoadingEnabled = true;
        }

        public new IDbSet<T> Set<T>() where T : class
        {
            return base.Set<T>();
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            var mappers = ((Object)this).GetType().Assembly.GetTypes().Where(m => IsSubclassOfRawGeneric(typeof(EntityTypeConfiguration<>), m));

            foreach (var modelMap in mappers)
            {
                dynamic mapper = Activator.CreateInstance(modelMap);
                modelBuilder.Configurations.Add(mapper);
            }
        }

        bool IsSubclassOfRawGeneric(Type generic, Type toCheck)
        {
            while (toCheck != null && toCheck != typeof(object))
            {
                var cur = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck;
                if (generic == cur)
                {
                    return true;
                }
                toCheck = toCheck.BaseType;
            }
            return false;
        }
    }
}